package utils

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"

	log "github.com/zeromicro/go-zero/core/logx"

	"github.com/zeromicro/go-zero/rest/httpc"
)

type UserInfo struct {
	Login             string `json:"login"`
	UID               string `json:"id"`
	URL               string `json:"url"`
	Name              string `json:"name"`
	Company           string `json:"company"`
	Blog              string `json:"blog"`
	Location          string `json:"location"`
	Email             string `json:"email"`
	Bio               string `json:"bio"`
	Followers         int    `json:"followers"`
	Following         int    `json:"following"`
	Phone             string `json:"phone"`
	AvatarURL         string `json:"avatar_url"`
	HTMLURL           string `json:"html_url"`
	HideEmail         int    `json:"hide_email"`
	PublicRepos       int    `json:"public_repos"`
	CreatedAt         string `json:"created_at"`
	UpdatedAt         string `json:"updated_at"`
	TotalRepos        int    `json:"total_repos"`
	TotalPrivateRepos int    `json:"total_private_repos"`
	OwnedPrivateRepos int    `json:"owned_private_repos"`
}

type CommitInfo struct {
	Name    string `json:"name"`
	Email   string `json:"email"`
	Message string `json:"message"`
}

// 定义Label结构体来匹配JSON对象
type Label struct {
	Id           string      `json:"id"`
	Name         string      `json:"name"`
	Color        string      `json:"color"`
	Desc         interface{} `json:"desc"`
	RepositoryId string      `json:"repository_id"`
	CreatedAt    string      `json:"created_at"`
	UpdatedAt    string      `json:"updated_at"`
}

// 调用Open API 生成评论
func CreatePRComment(owner, repo, pull_number, body, commit_id, token string) error {
	url := "https://api.atomgit.com/repos/" + owner + "/" + repo + "/pulls/" + pull_number + "/comments"

	type Request struct {
		Body string `json:"body"`
		CID  string `json:"commit_id"`
	}
	data := Request{
		Body: body,
		CID:  commit_id,
	}
	// 将结构体转为 JSON 数据
	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Error(err)
		return err
	}
	r, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Error(err)
		return err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/json")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		log.Error(err_)
		return err
	}
	defer res.Body.Close()
	// out, err := io.ReadAll(res.Body)
	// if err != nil {
	// 	log.Errorf("Failed to read response body:%s", err)
	// 	return err
	// }
	log.Debug(res.StatusCode)
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		return nil
	}
	return errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))
}

// 查询commit提交信息，获取message字段
func GetCommitsInfo(owner, repo, commit_id, token string) (*CommitInfo, error) {
	url := "https://api.atomgit.com/repos/" + owner + "/" + repo + "/commits/" + commit_id

	r, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/json")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		log.Error(err_)
		return nil, err
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Errorf("Failed to read response body:%s", err)
		return nil, err
	}
	info := CommitInfo{}
	log.Debug(res.StatusCode)
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		var keyValue map[string]interface{}
		err = json.Unmarshal(body, &keyValue)
		if err == nil {
			//fmt.Printf("#v\n", keyValue)
			if message, ok := keyValue["message"].(string); ok {
				log.Debugf("message: %s", message)
				info.Message = message
			}
			// 提取commit中的committer的name和email
			if commit, ok := keyValue["commit"].(map[string]interface{}); ok {
				if committer, ok := commit["committer"].(map[string]interface{}); ok {
					if name, ok := committer["name"].(string); ok {
						log.Debugf("Committer Name:%s", name)
						info.Name = name
					}
					if email, ok := committer["email"].(string); ok {
						log.Debugf("Committer Email:%s", email)
						info.Email = email
					}
				}
			}
			return &info, nil
		}

	}
	return nil, errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))
}

// 给pr打标签接口
func CreatePRLabels(owner, repo, pull_number, token string, lables []string) error {
	url := "https://api.atomgit.com/repos/" + owner + "/" + repo + "/pulls/" + pull_number + "/labels"

	type Request struct {
		Lables []string `json:"label_name_list"`
	}
	data := Request{
		Lables: lables,
	}
	// 将结构体转为 JSON 数据
	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Error(err)
		return err
	}
	r, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Error(err)
		return err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/json")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		log.Error(err_)
		return err
	}
	defer res.Body.Close()
	// out, err := io.ReadAll(res.Body)
	// if err != nil {
	// 	log.Errorf("Failed to read response body:%s", err)
	// 	return err
	// }
	log.Debug(res.StatusCode)
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		return nil
	}
	return errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))

}

// 获取用户邮箱
func GetUserEmail(token string) (string, error) {
	url := "https://api.atomgit.com/user/emails"

	r, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Error(err)
		return "", err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/json")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		log.Error(err_)
		return "", err
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Errorf("Failed to read response body:%s", err)
		return "", err
	}
	log.Debug(res.StatusCode)
	email_ := ""
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		var keyValue []map[string]interface{}
		err = json.Unmarshal(body, &keyValue)
		if err == nil {
			//fmt.Printf("#v\n", keyValue)
			// if message, ok := keyValue["message"].(string); ok {
			// 	log.Debugf("message: %s", token)
			// 	return message, nil
			// }
			// 遍历map切片并获取email字段
			for _, item := range keyValue {
				if email, ok := item["email"].(string); ok { // 类型断言
					fmt.Println("Email:", email)
					email_ = email
					break
				} else {
					fmt.Println("Email field not found or not a string")
				}
			}
			return email_, err
		}

	}
	return "", errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))
}

// 获取个人用户信息
func GetUserInfo(token string) (*UserInfo, error) {
	url := "https://api.atomgit.com/user/info"

	r, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/json")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err := http.DefaultClient.Do(r)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Errorf("Failed to read response body: %s", err)
		return nil, err
	}

	log.Debug(res.StatusCode)
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		var user UserInfo
		err = json.Unmarshal(body, &user)
		if err != nil {
			log.Errorf("Error unmarshalling response:%s", err.Error())
			return nil, err
		}
		return &user, nil // 返回 User 的指针
	}

	return nil, errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))
}

// 创建DCO预制标签接口
func CreateDcoLabels(owner, repo, name, color, token string) error {
	urls := "https://api.atomgit.com/repos/" + owner + "/" + repo + "/labels"

	// 创建表单数据
	formData := url.Values{}
	formData.Add("name", name)
	formData.Add("color", color) //绿色
	//formData.Add("name", "DCO Signed")
	//formData.Add("color", "#00FF00") //绿色
	// 如果需要添加更多的标签，可以继续使用 formData.Add
	//formData.Add("name", "DCO Failed")
	//formData.Add("color", "#FF0000") //红色

	// 编码表单数据
	data := formData.Encode()

	r, err := http.NewRequest("POST", urls, bytes.NewBuffer([]byte(data)))
	if err != nil {
		log.Error(err)
		return err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		log.Error(err_)
		return err
	}
	defer res.Body.Close()
	// out, err := io.ReadAll(res.Body)
	// if err != nil {
	// 	log.Errorf("Failed to read response body:%s", err)
	// 	return err
	// }
	log.Debug(res.StatusCode)
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		return nil
	}
	return errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))
}

// 获取DCO预制标签接口 获取仓库所有标签
func GetDcoLabels(owner, repo, token string) ([]string, error) {
	urls := "https://api.atomgit.com/repos/" + owner + "/" + repo + "/labels"

	r, err := http.NewRequest("GET", urls, nil)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	// 设置请求头
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Set("Authorization", "Bearer "+token)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		log.Error(err_)
		return nil, err
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Errorf("Failed to read response body:%s", err)
		return nil, err
	}
	log.Debug(res.StatusCode)
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		// 解析JSON数据
		var labels []Label
		err := json.Unmarshal([]byte(body), &labels)
		if err != nil {
			log.Errorf("解析JSON失败:%s", err.Error())
			return nil, err
		}

		// 获取name字段存入字符串数组
		var names []string
		for _, lb := range labels {
			names = append(names, lb.Name)
		}
		return names, nil
	}
	return nil, errors.New("error, status: " + res.Status + " code: " + fmt.Sprintf("%d", res.StatusCode))
}
